package com.aiti.lulian.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.response.inquiryorder.Buyer;
import com.aiti.lulian.entity.response.inquiryorder.BuyerBackGroupListResp;
import com.aiti.lulian.entity.response.inquiryorder.InquiryOrderDetailResponse;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.XunJiaRepsonse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName LuLianSupplierInquiryOrderServiceImpl
 * @Description
 * @Author diaozhende
 * @Date 2024/6/12 0012 15:27
 */
@Service
public class LuLianSupplierInquiryOrderServiceImpl extends BaseSerivceImpl<ILuLianSupplierInquiryOrderMapper, LuLianSupplierInquiryOrder> implements ILuLianSupplierInquiryOrderService {

    @Resource
    private ILuLianSupplierInquiryOrderGoodsService supplierInquiryOrderGoodsService;
    @Resource
    private ILuLianSupplierInquiryOrderRequestService supplierInquiryOrderRequestService;

    @Resource
    ILuLianSupplierInquiryOrderMapper supplierInquiryOrderMapper;
    @Resource
    private ILuLianSupplierInquiryOrderAttachmentService supplierInquiryOrderAttachmentService;
    @Resource
    private ISysDataService sysDataService;
    @Resource
    private ILuLianEnterpriseService luLianEnterpriseService;
    @Resource
    private ILuLianCertificateService certificateService;

    @Resource
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;

    @Autowired
    private LuLianRecruitmentMapper luLianRecruitmentJsGzMapper;

    @Autowired
    private SysAreaMapper  sysAreaMapper;

    @Resource
    private LuLianSupplierSignUpMapper luLianSupplierSignUpMapper;

    @Resource
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;

    @Resource
    private LuLianEnterpriseMapper luLianEnterpriseMapper;

    @Resource
    private ILuLianSupplierInquiryOrderMapper luLianSupplierInquiryOrderMapper;

    @Resource
    private ILuLianSupplierInquiryOrderGoodsMapper luLianSupplierInquiryOrderGoodsMapper;
    @Resource
    private ILuLianSupplierInquiryOrderRequestMapper luLianSupplierInquiryOrderRequestMapper;


    /**
     * 多参数查询
     *
     * @param supplierInquiryOrder 查询参数
     * @return java.util.List<com.aiti.lulian.entity.LuLianSupplierInquiryOrder>
     * @date 2024/6/12 0012 15:30
     * @author diaozhende
     */
    @Override
    public List<LuLianSupplierInquiryOrder> queryByParams(LuLianSupplierInquiryOrder supplierInquiryOrder) {
        return baseMapper.queryByParams(supplierInquiryOrder);
    }

    /**
     * 分页查询
     *
     * @param page                 当前页
     * @param pageSize             每页显示条数
     * @param supplierInquiryOrder 查询参数
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.aiti.lulian.entity.LuLianSupplierInquiryOrder>
     * @date 2024/6/12 0012 15:33
     * @author diaozhende
     */
    @Override
    public Page<LuLianSupplierInquiryOrder> queryPage(int page, int pageSize, LuLianSupplierInquiryOrder supplierInquiryOrder) {
        Page<LuLianSupplierInquiryOrder> queryPage = baseMapper.queryPage(new Page<LuLianSupplierInquiryOrder>(page, pageSize), supplierInquiryOrder);

        List<LuLianSupplierInquiryOrder> records = queryPage.getRecords();
        for (LuLianSupplierInquiryOrder order : records) {
            LambdaQueryWrapper<LuLianSupplierInquiryOrderRequest> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LuLianSupplierInquiryOrderRequest::getOrderId, order.getBaseId());
            LuLianSupplierInquiryOrderRequest request = luLianSupplierInquiryOrderRequestMapper.selectOne(wrapper);
            order.setSupplierInquiryOrderRequest(request);
        }
        queryPage.setRecords(records);

        return queryPage;
    }

    /**
     * 保存
     *
     * @param supplierInquiryOrder 保存数据
     * @return void
     * @date 2024/6/13 0013 9:01
     * @author diaozhende
     */
    @Override
    @Transactional
    public int saveData(LuLianSupplierInquiryOrder supplierInquiryOrder) {
        boolean res1 = this.save(supplierInquiryOrder);

        if (CollectionUtil.isNotEmpty(supplierInquiryOrder.getGoodsDataList())) {
            for (LuLianSupplierInquiryOrderGoods goods : supplierInquiryOrder.getGoodsDataList()) {
                goods.setOrderId(supplierInquiryOrder.getBaseId());
                boolean res2 = supplierInquiryOrderGoodsService.save(goods);
                if (!res2) {
                    return 0;
                }
            }
        }

        if (CollectionUtil.isNotEmpty(supplierInquiryOrder.getFileList())) {
            for (LuLianSupplierInquiryOrderAttachment attachment : supplierInquiryOrder.getFileList()) {
                attachment.setOrderId(supplierInquiryOrder.getBaseId());
                boolean res3 = supplierInquiryOrderAttachmentService.save(attachment);
                if (!res3) {
                    return 0;
                }
            }
        }
        supplierInquiryOrder.getSupplierInquiryOrderRequest().setOrderId(supplierInquiryOrder.getBaseId());
        supplierInquiryOrder.getSupplierInquiryOrderRequest().setCreator(supplierInquiryOrder.getCreator());
        boolean res4 = supplierInquiryOrderRequestService.save(supplierInquiryOrder.getSupplierInquiryOrderRequest());

        if (res1 && res4) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 通过id查回招暮单回显
     *
     * @param id
     */
    public LuLianSupplierInquiryOrder queryZmById(String id){
        LuLianSupplierInquiryOrder luLianSupplierInquiryOrder = luLianSupplierInquiryOrderMapper.selectById(id);
        if(luLianSupplierInquiryOrder != null){
            List<LuLianSupplierInquiryOrderGoods> goodsList = luLianSupplierInquiryOrderGoodsMapper.selectList(new QueryWrapper<LuLianSupplierInquiryOrderGoods>().eq("order_id", luLianSupplierInquiryOrder.getBaseId()));
            luLianSupplierInquiryOrder.setGoodsDataList(goodsList);
            LuLianSupplierInquiryOrderRequest luLianSupplierInquiryOrderRequest = luLianSupplierInquiryOrderRequestMapper.selectOne(new QueryWrapper<LuLianSupplierInquiryOrderRequest>().eq("order_id", luLianSupplierInquiryOrder.getBaseId()));
            luLianSupplierInquiryOrder.setSupplierInquiryOrderRequest(luLianSupplierInquiryOrderRequest);
        }
        return luLianSupplierInquiryOrder;
    }

    @Override
    public Message queryStataus(String userId) {
        long haveInHand = 0;
        long jieZhi = 0;
        List<XunJiaRepsonse> list = luLianSupplierSignUpMapper.selectCurrentBmList(userId);
        if(list != null && list.size() > 0){
            long count = list.stream().filter(k -> {
                if(StringUtils.equals("1", k.getSignupDeadlineDateType())) {
                    return true;
                }else if(StringUtils.equals("2", k.getSignupDeadlineDateType())){
                    Date signupDeadlineDate = k.getSignupDeadlineDate();
                    if(signupDeadlineDate == null){
                        return false;
                    }
                    if(DateUtil.date().isBefore(signupDeadlineDate)){
                        return true;
                    }
                    return false;
                }
                return false;
            }).count();
            haveInHand = haveInHand + count;

            long jiezhi = list.stream().filter(k -> {
                if(StringUtils.equals("2", k.getSignupDeadlineDateType())){
                    Date signupDeadlineDate = k.getSignupDeadlineDate();
                    if(signupDeadlineDate == null){
                        return false;
                    }
                    if(DateUtil.date().isAfter(signupDeadlineDate)){
                        return true;
                    }
                    return false;
                }
                return false;
            }).count();
            jieZhi = jieZhi + jiezhi;
        }
        Map<String,Long> countMap = new HashMap<>(16);
        countMap.put("jieZhi",jieZhi);
        countMap.put("haveInHand",haveInHand);
        return Message.success(countMap);
    }

    /**
     * 根据id 查询
     *
     * @param id
     * @return
     * @date 2024/6/19
     * @author yangfenzhen
     */
    @Override
    public LuLianSupplierInquiryOrderRequest queryById(String id) {
        LuLianSupplierInquiryOrderRequest orderRequest = baseMapper.queryById(id);
        if (orderRequest.getCreator() != null) {
            LuLianEnterprise enterprise = luLianEnterpriseService.getOne(new QueryWrapper<LuLianEnterprise>()
                    .eq("base_id", orderRequest.getCreator()));
            orderRequest.setCreator(enterprise.getBaseName());
        }
        List<String> businessModelList = Arrays.asList(orderRequest.getBusinessModel().split(","));
        List<SysData> sysDataBusinessModelList = sysDataService.list(new QueryWrapper<SysData>()
                .in("base_id", businessModelList));

        if (!sysDataBusinessModelList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (SysData sysData : sysDataBusinessModelList) {
                for (int i = 0; i < businessModelList.size(); i++) {
                    if (sysData.getBaseId().equals(businessModelList.get(i))) {
                        sb.append(sysData.getBaseName()).append(",");
                    }
                }

            }
            String result = sb.toString();
            orderRequest.setBusinessModel(result.substring(0, result.length() - 1));
        }

        List licenseRequestList = Arrays.asList(orderRequest.getLicenseRequest().split(","));
        List<SysData> sysDataLicenseRequestList = sysDataService.list(new QueryWrapper<SysData>()
                .in("base_id", licenseRequestList));
        if (!sysDataLicenseRequestList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (SysData sysData : sysDataLicenseRequestList) {
                for (int i = 0; i < licenseRequestList.size(); i++) {
                    if (sysData.getBaseId().equals(licenseRequestList.get(i))) {
                        sb.append(sysData.getBaseName()).append(",");
                    }
                }
            }
            String result = sb.toString();
            orderRequest.setLicenseRequest(result.substring(0, result.length() - 1));
        }

        List otherLicensetList = Arrays.asList(orderRequest.getOtherLicense().split(","));
        List<LuLianCertificate> certificateList = certificateService.list(new QueryWrapper<LuLianCertificate>()
                .in("base_id", otherLicensetList));
        if (!certificateList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (LuLianCertificate certificate : certificateList) {
                for (int i = 0; i < otherLicensetList.size(); i++) {
                    if (certificate.getBaseId().equals(otherLicensetList.get(i))) {
                        sb.append(certificate.getBaseName()).append(",");
                    }
                }
            }
            String result = sb.toString();
            orderRequest.setOtherLicense(result.substring(0, result.length() - 1));
        }
        return orderRequest;
    }

    @Override
    public Map<String, Object> queryCount(String userId) {
        Map<String, Object> map = new HashMap<>();

        //招募中总数
        Integer isNotExpiredCount = supplierInquiryOrderMapper.selectIsNotExpiredCount(userId);
        //已截止总数
        Integer isExpiredCount = supplierInquiryOrderMapper.selectIsExpiredCount(userId);
        //已停用总数
        Integer isDelCount = supplierInquiryOrderMapper.selectIsDelCount(userId);

        map.put("isNotExpiredCount", isNotExpiredCount);
        map.put("isExpiredCount", isExpiredCount);
        map.put("isDelCount", isDelCount);

        return map;
    }

    @Transactional
    @Override
    public int updateDataById(LuLianSupplierInquiryOrder supplierInquiryOrder) {
        boolean res1 = this.updateById(supplierInquiryOrder);

        if (CollectionUtil.isNotEmpty(supplierInquiryOrder.getGoodsDataList())) {
            List<LuLianSupplierInquiryOrderGoods> goodsDataList = supplierInquiryOrder.getGoodsDataList();
//            for (LuLianSupplierInquiryOrderGoods goods : goodsDataList) {
//                boolean res2 = supplierInquiryOrderGoodsService.save(goods);
//                if (!res2) {
//                    return 0;
//                }
//            }

            List<LuLianSupplierInquiryOrderGoods> collect = goodsDataList.stream().peek(k -> k.setOrderId(supplierInquiryOrder.getBaseId())).collect(Collectors.toList());

            boolean res2 = supplierInquiryOrderGoodsService.saveOrUpdateBatch(collect);
            if (!res2) {
                return 0;
            }
        }

        if (CollectionUtil.isNotEmpty(supplierInquiryOrder.getFileList())) {
//            LambdaQueryWrapper<LuLianSupplierInquiryOrderAttachment> orderWrapper = new LambdaQueryWrapper<>();
//            orderWrapper.eq(LuLianSupplierInquiryOrderAttachment::getOrderId, supplierInquiryOrder.getBaseId());


            QueryWrapper<LuLianSupplierInquiryOrderAttachment> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("order_id", supplierInquiryOrder.getBaseId());


            boolean res4 = supplierInquiryOrderAttachmentService.remove(orderWrapper);
//            if (!res4) {
//                return 0;
//            }
            for (LuLianSupplierInquiryOrderAttachment attachment : supplierInquiryOrder.getFileList()) {
                attachment.setOrderId(supplierInquiryOrder.getBaseId());
                attachment.setBaseId(IdUtil.simpleUUID());
                boolean res5 = supplierInquiryOrderAttachmentService.save(attachment);
                if (!res5) {
                    return 0;
                }
            }
        }

        boolean res3 = true;
        if (supplierInquiryOrder.getSupplierInquiryOrderRequest() != null) {
            res3 = supplierInquiryOrderRequestService.updateById(supplierInquiryOrder.getSupplierInquiryOrderRequest());

        }

        if (res1 && res3) {
            return 1;
        } else {
            return 0;
        }
    }

    @Transactional
    @Override
    public LuLianSupplierInquiryOrder queryByBaseId(String baseId) {
        LuLianSupplierInquiryOrder luLianSupplierInquiryOrder = supplierInquiryOrderMapper.selectById(baseId);

        LambdaQueryWrapper<LuLianSupplierInquiryOrderGoods> goodsWrapper = new LambdaQueryWrapper<>();
        goodsWrapper.eq(LuLianSupplierInquiryOrderGoods::getOrderId, baseId);
        List<LuLianSupplierInquiryOrderGoods> goodsList = supplierInquiryOrderGoodsService.list(goodsWrapper);
        luLianSupplierInquiryOrder.setGoodsDataList(goodsList);

        LambdaQueryWrapper<LuLianSupplierInquiryOrderAttachment> attachmentWrapper = new LambdaQueryWrapper<>();
        attachmentWrapper.eq(LuLianSupplierInquiryOrderAttachment::getOrderId, baseId);
        List<LuLianSupplierInquiryOrderAttachment> attachmentList = supplierInquiryOrderAttachmentService.list(attachmentWrapper);
        luLianSupplierInquiryOrder.setFileList(attachmentList);

        LambdaQueryWrapper<LuLianSupplierInquiryOrderRequest> requestWrapper = new LambdaQueryWrapper<>();
        requestWrapper.eq(LuLianSupplierInquiryOrderRequest::getOrderId, baseId);
        LuLianSupplierInquiryOrderRequest supplierInquiryOrderRequest = supplierInquiryOrderRequestService.getOne(requestWrapper);
        luLianSupplierInquiryOrder.setSupplierInquiryOrderRequest(supplierInquiryOrderRequest);

        return luLianSupplierInquiryOrder;
    }

    /**
     * 查询招募单回显
     *
     * @param recruitId 招募单Id
     * @param userId    用户Id
     */
    @Override
    public Message queryShowSupplierInquiryOrderRecruit(String recruitId, String userId,String type) {
        List<LuLianEnterpriseUser> userBindEnterpriseList = luLianEnterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if (userBindEnterpriseList == null || userBindEnterpriseList.size() != 1) {
            return Message.fail("该账号没进行企业认证！");
        }

        //返回前端的数据
        InquiryOrderDetailResponse response = new InquiryOrderDetailResponse();

        //查询卖家方信息
        LuLianEnterpriseUser enterpriseUser = userBindEnterpriseList.get(0);
        LuLianEnterprise sellerInfo = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().select("base_name","unicode","base_id").eq("base_id",enterpriseUser.getEnterpriseId()).eq("status","1"));
        if(sellerInfo == null){
            return Message.fail("该账号没进行企业认证或者企业认证未通过");
        }
        response.setSellerInfo(sellerInfo);

        BuyerSellerInfo buyerSellerInfo = selectBuyInfo(type, recruitId);

        if(buyerSellerInfo == null){
            return Message.fail(6666,"没有获取到买家信息");
        }

        Buyer buyer = Buyer.builder()
                .orderId(buyerSellerInfo.getBaseId())
                .receivingAddress(buyerSellerInfo.getAddress())
                .enterpriseName(buyerSellerInfo.getEnterpriseName())
                .enterpriseId(buyerSellerInfo.getEnterpriseId())
                .maiJiaUserId(buyerSellerInfo.getMaiJiaUserId())
                .build();

        response.setBuyerInfo(buyer);

        //获取当前登陆用户报价的信息
        LuLianSupplierSignUp luLianSupplierSignUp = luLianSupplierSignUpMapper.selectOne(new QueryWrapper<LuLianSupplierSignUp>().eq("order_id", recruitId).eq("creator", userId));
        response.setLuLianSupplierSignUp(luLianSupplierSignUp);
        return Message.success(response);
    }

    private BuyerSellerInfo selectBuyInfo(String type,String recruitId){
        if(StringUtils.equals(type,"1")){
            //查询买家方信息
            Map<String, Object> buyerInfo = baseMapper.selectBuyerInfo(recruitId);

            Object enterpriseId = buyerInfo.get("enterprise_id");
            if(enterpriseId == null || StringUtils.isBlank(String.valueOf(enterpriseId))){
                return null;
            }

            //收货地址的拼接
            StringBuilder receivingAddress = new StringBuilder();

            //查询企业实际所在地
            LuLianEnterpriseHistoryCi luLianEnterpriseHistoryCi = luLianEnterpriseHistoryMapper.selectCompanyActualAddress(String.valueOf(enterpriseId));
            if(luLianEnterpriseHistoryCi != null){

                if(StringUtils.isNotBlank(luLianEnterpriseHistoryCi.getActualProvince())){
                    receivingAddress.append(luLianEnterpriseHistoryCi.getActualProvince());
                }

                if(StringUtils.isNotBlank(luLianEnterpriseHistoryCi.getActualCity())){
                    receivingAddress.append("-").append(luLianEnterpriseHistoryCi.getActualCity());
                }


                if(StringUtils.isNotBlank(luLianEnterpriseHistoryCi.getActualCounty())){
                    receivingAddress.append("-").append(luLianEnterpriseHistoryCi.getActualCounty());
                }
            }
            BuyerSellerInfo info = BuyerSellerInfo.builder()
                    .address(receivingAddress.toString())
                    .baseId(String.valueOf(buyerInfo.get("base_id")))
                    .enterpriseName(String.valueOf(buyerInfo.get("enterprise_name")))
                    .enterpriseId(String.valueOf(buyerInfo.get("enterprise_id")))
                    .build();
            Object creator = buyerInfo.get("creator");
            if(!Objects.isNull(creator)){
                String creatorStr = (String) creator;
                info.setMaiJiaUserId(creatorStr);
            }
            return info;
        }else if(StringUtils.equals(type,"2")){
            LuLianRecruitment recruitmentJsGz = luLianRecruitmentJsGzMapper.selectOne(new QueryWrapper<LuLianRecruitment>().eq("base_id", recruitId));
            if(recruitmentJsGz == null){
                return null;
            }
            BuyerSellerInfo info = BuyerSellerInfo.builder()
                    .enterpriseName(recruitmentJsGz.getCompanyName())
                    .enterpriseId("")
                    .maiJiaUserId(recruitmentJsGz.getCreator())
                    .baseId(recruitmentJsGz.getBaseId())
                    .build();
            StringBuilder addressBuilder = new StringBuilder();
            if(StringUtils.isNotBlank(recruitmentJsGz.getProvince())){
                SysArea sysArea = sysAreaMapper.selectById(recruitmentJsGz.getProvince());
                addressBuilder.append(sysArea.getBaseName());
            }
            if(StringUtils.isNotBlank(recruitmentJsGz.getCity())){
                SysArea sysArea = sysAreaMapper.selectById(recruitmentJsGz.getCity());
                addressBuilder.append("-").append(sysArea.getBaseName());
            }
            if(StringUtils.isNotBlank(recruitmentJsGz.getCounty())){
                SysArea sysArea = sysAreaMapper.selectById(recruitmentJsGz.getCounty());
                addressBuilder.append("-").append(sysArea.getBaseName());
            }
            if(StringUtils.isNotBlank(addressBuilder.toString())){
                info.setAddress(addressBuilder.toString());
            }
            return info;
        }
        return null;
    }

    /**
     * 查询供应商列表
     *
     * @param userId
     */
    @Override
    public List<BuyerBackGroupListResp> querySellSupplierInquiryOrderRecruit(String userId,Page page,String type) {
        List<BuyerBackGroupListResp> buyerBackGroupListResps = baseMapper.querySellSupplierInquiryOrderRecruit(page,userId,type);
        return buyerBackGroupListResps;
    }

    @Override
    public List<XunJiaRepsonse> queryBuyerInquiryOrderRecruit(String userId, Page page) {
        return luLianSupplierSignUpMapper.selectCustomPage(page,userId);
    }
}